﻿package com{

import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;

public class DragMomentum extends Sprite{

/* set some variables we will use later for drag DragMomentum*/

private var targetObject:Sprite = new Sprite;

private var posAv:int = 0;
private var posBv:int = 0;

private var posAh:int = 0;
private var posBh:int = 0;

private var trajh:int = 0;
private var trajv:int = 0;

private var drag:int = 0;

//NOTE: the higher the framerate, the lower the friction needs to be;
private var friction:Number = 1.18;



public function DragMomentum():void{

}

public function gin(target:MovieClip):void{
		
		targetObject = target;
		targetObject.addEventListener(MouseEvent.MOUSE_DOWN, dragger);
		targetObject.addEventListener(MouseEvent.MOUSE_UP, dropper);
		targetObject.addEventListener(Event.MOUSE_LEAVE, dropper);
	}

private function dragger(e:MouseEvent):void{

trace("drag starting"+e.target);

targetObject = e.target as MovieClip;

e.target.startDrag();
drag = 1;

addEventListener(Event.ENTER_FRAME, momentum);


}
/*We stop dragging and set the drag value to 0*/

private function dropper(e:MouseEvent):void{
e.target.stopDrag();
drag = 0;
}


private function momentum(e:Event):void{

if (drag==1){
trace("recording trajectory");

/* Calculate Y trajectory/velocity*/
posBv = posAv;
posAv = mouseY;
trajv = posBv-posAv;
/* Calculate X trajectory/velocity*/
posBh = posAh;
posAh = mouseX;
trajh = posBh-posAh;
trace("v:"+trajv);
trace("h:"+trajh);

}else if(drag==0){
trace("moving to final trajectory");

trajh = trajh/friction;
trajv = trajv/friction;
trace("v:"+trajv);
trace("h:"+trajh);
targetObject.x -= Math.round(trajh);
targetObject.y -= Math.round(trajv);
if (trajh==0 && trajv==0){
trace("got to destination");
removeEventListener(Event.ENTER_FRAME, momentum);
}
}
}
}
}